package com.bussiness.xutai.controller;

import com.bussiness.xutai.bean.RespBean;
import com.bussiness.xutai.bean.User;
import com.bussiness.xutai.service.UserService;
import com.bussiness.xutai.util.MD5Util;
import com.bussiness.xutai.util.session.SessionConst;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

import static org.apache.solr.client.solrj.impl.XMLResponseParser.log;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    HttpSession session;

    @RequestMapping("user_test")
    @ResponseBody
    public User testUser(String account){
        log.info("日志打印>>>>>>>>>>>>>>>>>>>>>");
        return userService.getUserByAccount(account);
    }

    //用户登录接口
    @RequestMapping("user_login")
    @ResponseBody
    public RespBean userLogin(String password,String account){
        int a = userService.getCount(account);
        if(a > 1){
            return RespBean.error("用户名已存在");
        }
        User user = userService.getUserByAccount(account);
        log.info(user+"查询到用户");
        if(StringUtils.isBlank(account)){
            return RespBean.error("用户名为空");
        }
        if(StringUtils.isBlank(password)){
            return RespBean.error("密码为空");
        }
        if(null == user){
            return RespBean.error("用户名不存在");
        }
        if(!MD5Util.encrypt(password).equals(user.getPassword())){
            return RespBean.error("密码错误");
        }

        session.setAttribute(SessionConst.SESSION_USER,user);
        return RespBean.ok("登陆成功");
    }

    //得到当前登录的用户
    @RequestMapping("showUser")
    @ResponseBody
    public User showUser(){
        User user = (User) session.getAttribute(SessionConst.SESSION_USER);
        return user;
    }

    //退出登录，并清除session
    @RequestMapping("logout")
    public String logout(User user) {
        session.invalidate();
        return "redirect:url";
    }
}
